package cc.zy.base.businesses.controller;

import cc.zy.base.businesses.entity.*;
import cc.zy.base.businesses.service.ICollegeService;
import cc.zy.base.businesses.utils.StudyTypeVal;
import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.CreatePdfUtil;
import cc.zy.base.common.utils.FebsUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.Image;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * 院校
 * Controller
 *
 * @author Jiangjinlin
 * @date 2021-01-18 10:51:13
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
@RequestMapping("college")
public class CollegeController extends BaseController {

    @Resource
    private final ICollegeService collegeService;

    @GetMapping(FebsConstant.VIEW_BUS_PREFIX + "college")
    public String collegeIndex() {
        return FebsUtil.BusinessView("college/college");
    }

    @GetMapping("list")
    @ResponseBody
    public FebsResponse collegeList(QueryRequest request, College college) {
        log.debug("前台传来的对象是：" + college);
        Map<String, Object> dataTable = getDataTable(collegeService.findColleges(request, college));
        return new FebsResponse().success().data(dataTable);
    }

    @PostMapping("add")
    @ResponseBody
    @ControllerEndpoint(operation = "新增院校", exceptionMessage = "新增院校异常")
    public FebsResponse addCollege(@Valid College college) {
        System.out.println("college = =======================" + college);
        String regex = "^[\\u4e00-\\u9fa5]{0,}$";
        String value = college.getPrincipalName();
        System.out.println("value = " + value);
        boolean match = FebsUtil.match(regex, value);
        System.out.println("match = " + match);
        if (!match) {
            throw new RuntimeException("名字必须为汉字！！");
        }
        log.info("前台传来的图片地址为+" + college.getImgUrl());
        college.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
        college.setStudyType(StudyTypeVal.val);
        collegeService.createCollege(college);
        return new FebsResponse().success();
    }

    @PostMapping("collegeImgUpload")
    @ResponseBody
    @ControllerEndpoint(operation = "上传院校签章", exceptionMessage = "上传院校签章失败")
    public FebsResponse collegeImgUpload(@RequestParam("file") MultipartFile multipartFile) {

        log.debug(String.format("multipartFile = %s", multipartFile));

        if (multipartFile != null && multipartFile.getSize() > 0) {
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            String realPath = "D:\\\\info\\\\collegeImg\\\\" + new Date().getTime() + "." + suffix;
            File newfile = new File(realPath);
            try {
                multipartFile.transferTo(newfile);
                return new FebsResponse().message(realPath);
            } catch (IOException e) {
                e.printStackTrace();
                return new FebsResponse().message("上传院校签章失败");
            }

        } else {
            return new FebsResponse().message("上传院校签章,文件为空");
        }
    }

    @GetMapping("delete/{collegeIds}")
    @ControllerEndpoint(operation = "删除院校", exceptionMessage = "删除院校异常")
    @ResponseBody
    public FebsResponse deleteColleges(@NotBlank(message = "{required}") @PathVariable String collegeIds) {
        String[] ids = collegeIds.split(StringPool.COMMA);
        collegeService.deleteColleges(ids);
        return new FebsResponse().success();
    }

    @PostMapping("update")
    @ControllerEndpoint(operation = "修改院校", exceptionMessage = "修改院校信息异常")
    @ResponseBody
    public FebsResponse updateCollege(@Valid College college) {
        log.debug("修改院校id：" + college.getId());
        if (college.getId() == null) {
            throw new FebsException("院校ID为空");
        }
        college.setUpdateUserId(FebsUtil.getCurrentUser().getUserId());
        collegeService.updateCollege(college);
        return new FebsResponse().success();
    }


    @GetMapping("excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, College college) {

        log.debug(String.format("response = %s", response));
        log.debug(String.format("college = %s", college));

        List<College> colleges = collegeService.findCollageListNotPage(college);
        ExcelKit.$Export(College.class, response).downXlsx(colleges, false);
    }

    /**
     * 方法描述：查找院校简称
     *
     * @param collegeId 院校id
     * @return cc.zy.base.common.entity.FebsResponse
     * @author houweikang
     * @date 2021/2/3
     */
    @GetMapping("findById/{collegeId}")
    @ResponseBody
    public FebsResponse findById(@PathVariable Integer collegeId) {

        log.debug(String.format("collegeId = %s", collegeId));

        College college = collegeService.findById(collegeId);
        return new FebsResponse().success().data(college);
    }

    /**
     * 方法描述：获取所有有效批次[id、名称]，倒序
     *
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/6
     */
    @ResponseBody
    @GetMapping("batchSelect")
    public FebsResponse findBatchForSelect() {

        List<Batch> batchList = collegeService.findBatchForSelect();
        log.debug(String.format("batchList = %1$s", batchList));

        return new FebsResponse().success().data(batchList);
    }

    /**
     * 方法描述：查询所有院校[id、名称]
     *
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/9
     */
    @ResponseBody
    @GetMapping("collegeSelect")
    public FebsResponse findCollegeForSelect() {

        List<College> collegeList = collegeService.findCollegeForSelect();
        log.debug(String.format("collegeList = %1$s", collegeList));

        return new FebsResponse().success().data(collegeList);
    }

    /**
     * 方法描述：根据院校id查询层次[id、名称]，正序
     *
     * @param collegeId 院校id【必传项】
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/9
     */
    @ResponseBody
    @GetMapping("levelSelect")
    public FebsResponse findLevelForSelect(Integer collegeId) {

        log.debug(String.format("collegeId = %1$ 9d", collegeId));
        List<Level> levelList = collegeService.findLevelForSelect(collegeId);
        log.debug(String.format("levelList = %1$s", levelList));

        return new FebsResponse().success().data(levelList);
    }

    /**
     * 方法描述：根据院校id、层次id查询专业[id、名称]
     *
     * @param collegeId 院校id【必传项】
     * @param levelId   层次id【必传项】
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/9
     */
    @ResponseBody
    @GetMapping("majorSelect")
    public FebsResponse findMajorForSelect(Integer collegeId, Integer levelId) {

        log.debug(String.format("collegeId = %1$ 9d，levelId = %2$ 9d", collegeId, levelId));
        List<Major> majorList = collegeService.findMajorForSelect(collegeId, levelId);
        log.debug(String.format("majorList = %1$s", majorList));

        return new FebsResponse().success().data(majorList);
    }

    /**
     * 方法描述：查询所有学习形式(成教、网教、电大)
     *
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/9
     */
    @ResponseBody
    @GetMapping("studyTypeSelect")
    public FebsResponse findStudyTypeForSelect() {

        List<Dic> studyTypeList = collegeService.findStudyTypeForSelect();
        log.debug(String.format("studyTypeList = %1$s", studyTypeList));

        return new FebsResponse().success().data(studyTypeList);
    }

    /**
     * 方法描述：查询校区
     *
     * @return cc.zy.base.common.entity.FebsResponse
     * @author LiPeng
     * @date 2021/3/18
     */
    @ResponseBody
    @GetMapping("campusSelect")
    public FebsResponse findCampusForSelect() {

        List<Dic> CampusList = collegeService.findCampusForSelect();
        log.debug(String.format("CampusList = %1$s", CampusList));

        return new FebsResponse().success().data(CampusList);
    }

    /**
     * 增加功能中，查询前台输入的全称或简称是否存userAdd.html在
     *
     * @param name
     * @param simplename
     * @return Boolean false为重复
     * true为不重复
     */
    @GetMapping("isRepetitive")
    @ResponseBody
    public Boolean isRepetitive(String name, String simpleName) {
        return collegeService.isRepetitive(name, simpleName);
    }
}